/*
 *@author: YangJie
 *@date: 2021-04-09 10:49:49
 *@version:
 *@description: 参数设置->公共配置->班组
 */
import React, { Component } from 'react';
import { Table, Form, Row, Col, Radio, DatePicker } from 'antd';
import '@/assets/css/settings';
import { withRouter } from 'react-router-dom';
import { FileDown } from '../../../components_yyr/commponent/File';
import Paging from '../../../components_yyr/commponent/Paging';
// import 'echarts-gl';
import { euqApplicationName_gl } from '../../../config';
import moment from 'moment';

const {  RangePicker} = DatePicker
var date = new Date();
let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
let year = date.getFullYear()
let todayEnd = `${year}-${month}-${day} 23:59:59`
let todayStart = `${year}-${month}-01 00:00:00`
var chooseData;
var formValuesOld;
var valueOld;
var isNext;
class EquipmentTypeAnalyse4_errorList extends Component {
    constructor(props) {
        super(props);
        console.log(props);
        chooseData = props.record
        formValuesOld = props.formValues
        isNext = props.isNext
        valueOld = props.value
        console.log(chooseData)
    }

    state = {
        loading: false, //加载中...
        dataSource: [], //数据源
        drawerVisible: false, //新增修改抽屉的显示与隐藏
        chooseData: {}, //用checkbox选择好的数据
        total: 0, //总数据量
        formValues: {},
        weekList: [],
        value: valueOld,
        //  activeKey:'top',
        activeKey: 'top',
        thisMonth: [], lastMonth: [], last90Day: [], dateString: [], DepartmentList: [], EquTypeList: []
    };
    componentDidMount() {
        this.getDate()
        this.fetch({
            pageNum: 1,
            pageSize: 10,
            isNext:isNext===1 ? 1 : 0,
            timeList: [formValuesOld.startTime , formValuesOld.endTime],
            equTypeId:chooseData.equTypeId ? chooseData.equTypeId : formValuesOld.equTypeId ? formValuesOld.equTypeId : undefined,
            deptId:chooseData.deptId ? chooseData.deptId : formValuesOld.deptId ? formValuesOld.deptId : undefined,
            equId:chooseData.equId ? chooseData.equId : undefined
        });
    }
    //初始化加载数据
    fetch = data => {
        let str = ''
        console.log(data)
        if (data.timeList && data.timeList.length === 2) {
            data['startTime'] = data.timeList[0]
            data['endTime'] = data.timeList[1]
            delete data['timeList']
        } else if (!data.timeList || data.timeList.length === 0) {
            data['startTime'] = data['startTime'] ? data['startTime'] : ''
            data['endTime'] = data['endTime'] ? data['endTime'] : ''
            delete data['timeList']
        }
        if(!valueOld){
            this.props.form.setFieldsValue({
                'dateString' : [moment(data.startTime, 'YYYY/MM/DD'),moment(data.endTime, 'YYYY/MM/DD')]
            })
        }
        this.setState({ loading: true, formValues: data }, () => {
            console.log(this.state.formValues)
        })
        for (var key in data) {
            if (data[key] || data[key] == 0) {
                str += `&${key}=${data[key]}`
            }
        }
        this.get(`${euqApplicationName_gl}/equipmentDeptReport/findFaultNumList?` + str).then(res => {
            console.log(res.data.data)
            this.setState({
                loading: false,
                dataSource: res.data.data,
                total: res.data.total,
            });
        })
    };
    getDate = () => {
        var date = new Date();
        let day = date.getDate() < 10 ? `0${date.getDate()}` : date.getDate()
        let month = date.getMonth() + 1 ? `0${date.getMonth() + 1}` : date.getMonth() + 1
        let year = date.getFullYear()
        let todayEnd = `${year}-${month}-${day} 23:59:59`
        let todayStart = `${year}-${month}-01 00:00:00`
        let thisMonth = [todayStart, todayEnd]
        let lastMonth = this.getLastMonth()
        let last90Day = [this.getLast90Day(), todayEnd]
        this.setState({
            thisMonth, lastMonth, last90Day
        })
    }
    getLastMonth = () => {//获取上个月日期第一天
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() < 10 ? `0${nowDate.getMonth()}` : nowDate.getMonth();
        if (month == 0) {
            year = year - 1;
            month = 12;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 23:59:59';
        return [year + "-" + month + "-01 00:00:00", yyyyMMdd];
    }
    /**
     * 获取上个月月底日期
     */
    getLast90Day = () => {
        var nowDate = new Date();
        var year = nowDate.getFullYear();
        var month = nowDate.getMonth() - 2 < 10 ? `0${nowDate.getMonth() - 2}` : nowDate.getMonth() - 2;
        if (month == 0) {
            month = 12;
            year = year - 1;
        }
        var lastDay = new Date(year, month, 0);
        var day = lastDay.getDate() < 10 ? `0${lastDay.getDate()}` : lastDay.getDate();
        var yyyyMMdd = year + "-" + month + "-" + day + ' 00:00:00';
        return yyyyMMdd;
    }
    handleSizeChange = (e) => {
        console.log(`${e.target.value}`);
        this.props.form.resetFields('dateString')
        let value = e.target.value
        valueOld = e.target.value
        let data = { ...this.state.formValues }
        switch (value) {
            case '1': {
                data.timeList = this.state.thisMonth
                break;
            }
            case '2': {
                data.timeList = this.state.lastMonth
                break;
            }
            case '3': {
                data.timeList = this.state.last90Day
                break;
            }
            case '4': {
                data.timeList = ['','']
                break;
            }
        }
        this.setState({ value }, () => {
            this.fetch(data)
        })
    }
    onChange = (date, dateString) => {
        if (dateString.length === 2 && dateString[0] != '') {
            this.setState({ value: null, dateString })
            valueOld = null
            let data = { ...this.state.formValues }
            data.timeList = [dateString[0] + ' 00:00:00', dateString[1] + ' 23:59:59']
            this.fetch(data)
            console.log(date, dateString);
        } else {
            valueOld = '1'
            this.fetch({
                pageNum: 1,
                pageSize: 10,
                deptId: chooseData.deptId || chooseData.deptId === 0 ? chooseData.deptId : formValuesOld.deptId || formValuesOld.deptId === 0 ? formValuesOld.deptId : '',
                equTypeId: chooseData.equTypeId || chooseData.equTypeId === 0 ? chooseData.equTypeId : formValuesOld.equTypeId || formValuesOld.equTypeId === 0 ? formValuesOld.equTypeId : '',
                isNext: 1,
                timeList: [todayStart,todayEnd]
            })
        }
    }
    remove = (activeKey) => {
        this.props.history.push('/equipmentTypeAnalyse/new')
    }
    onChangeTabs = activeKey => {
        this.setState({ activeKey });
    };

    onEdit = (targetKey, action) => {
        this[action](targetKey);
    };

    onTestClick = (e) => {
        this.props.onEvent({ type: 'test', data: 0 });
    }
    add = (record, title, activeKey,isNext,data,valueOld) => {
        this.props.onEvent({ type: 'add', data: { record, title, activeKey,isNext ,data,valueOld} });
    }
    render() {
        const { chooseData, dataSource, loading, total, formValues, value } = this.state;
        const columns= [
            // { title: '序号', width: 100, dataIndex: 'id' },
            { title: '设备编号', width: 100, dataIndex: 'equCode',align:'center', },
            { title: '设备名称', width: 100, dataIndex: 'equName',align:'center', },
            { title: '规格型号', width: 100, dataIndex: 'equSpecsModel',align:'center', },
            { title: '设备类型', width: 100, dataIndex: 'equTypeName',align:'center', },
            { title: '报修时间', width: 100, dataIndex: 'time',align:'center', },
            { title: '部门', width: 100, dataIndex: 'deptName',align:'center', },
            { title: '维修用时(h)', width: 100, dataIndex: 'wxHours',align:'center', },
            { title: '停机时长(h)', width: 100, dataIndex: 'tjHours',align:'center', },
            { title: '维修费用(元）', width: 120, dataIndex: 'maintenanceCosts' ,align:'center',},
            { title: '维修班组', width: 100, dataIndex: 'team',align:'center', },
            { title: '主修人员', width: 100, dataIndex: 'majorStaff',align:'center', },
            { title: '故障原因', width: 100, dataIndex: 'faultReason' ,align:'center',},
            { title: '报修单号', width: 100, dataIndex: 'orderCode',align:'center', },
            { title: '维修状态', width: 100, dataIndex: 'statusName' ,align:'center',},
            { title: '维修单号', width: 100, dataIndex: 'repairCode' ,render:(text,record)=>{
                return <span><a href onClick={() => this.add(record,`${record.repairCode}-详细`,`${record.repairCode}_recordDetails`,1,formValues,valueOld)} style={{color:'red'}}>{text}</a></span>
            },align:'center',},

        ]
        return (
            <div className="shadow-radius">
                {/* <Button onClick={this.onTestClick}>test</Button>
                 <Tabs hideAdd
                     onChange={this.onChangeTabs}
                     activeKey={this.state.activeKey}
                     type="editable-card"
                     onEdit={this.onEdit}> */}
                {/* <TabPane tab="生产设备类型透视分析" key="top" closable={true}> */}
                {/* <Card>
                    <BasicForm formList={this.formList()} filterSubmit={this.filterSubmit} labelSpan={8} wrapperSpan={12} onRef={ref => (this.child = ref)} />
                </Card> */}
                <div>
                    <Row>
                        <Col span={20}>
                            <p>
                                <span>时间：</span>
                                <Radio.Group onChange={this.handleSizeChange} buttonStyle="solid" value={valueOld}>
                                    <Radio.Button value="1">本月</Radio.Button>
                                    <Radio.Button value="2">上月</Radio.Button>
                                    <Radio.Button value="3">90日</Radio.Button>
                                    <Radio.Button value="4">历史</Radio.Button>
                                </Radio.Group>
                                <Form style={{ display: 'inline-block' }}>
                                    <Form.Item>
                                        {this.props.form.getFieldDecorator('dateString', {
                                            // initialValue:[]defaultValue={dateString.length===2?[moment(dateString[0], 'YYYY/MM/DD'), moment(dateString[1], 'YYYY/MM/DD')]:''} 
                                        })(<RangePicker onChange={this.onChange} style={{ marginLeft: 25 }} placeholder={['开始时间', '结束时间']} />)}
                                    </Form.Item>
                                </Form>
                            </p>
                        </Col>
                            <Col style={{ float: 'right' }}><FileDown fileName="设备部门透视分析报表" buttonName="导出表" method="post" apiPath={`${euqApplicationName_gl}/equipmentTypeReport/importEquipmentTypeFaultCountTable`} data={formValues} /></Col>
                    </Row>
                </div>
                <Table columns={columns} rowKey={(record, index) => record.id} dataSource={dataSource} pagination={false} loading={loading} scroll={{ x: 'calc(700px + 50%)' }}/>
                <Paging total={total} formValues={formValues} fetch={pager => this.fetch(pager)} />
                {/* </TabPane>
                 </Tabs> */}
            </div>
        );
    }
}
export default Form.create()(withRouter(EquipmentTypeAnalyse4_errorList));
